<template>
    <div
        class="container-body article-detail-body"
        :style="{ width: proxy.globalInfo.bodyWidth + 'px' }"
        v-if="Object.keys(articleInfo).length > 0"
    >
        <!-- 板块导航 -->
        <div class="board-info">
            <router-link
                class="a-link"
                :to="`/forum/${articleInfo.pBoardId}`"
            >{{ articleInfo.pBoardName
                }}</router-link>
            <span class="iconfont icon-right"></span>
            <template v-if="articleInfo.boardId">
                <router-link
                    class="a-link"
                    :to="`/forum/${articleInfo.pBoardId}/${articleInfo.boardId}`"
                >{{
                    articleInfo.boardName
                    }}</router-link>
                <span class="iconfont icon-right"></span>
            </template>
            <span>{{ articleInfo.title }}</span>
        </div>
        <!-- 文章详情 -->
        <div
            class="detail-container"
            :style="{ width: proxy.globalInfo.bodyWidth - 300 + 'px' }"
        >
            <div class="article-detail">
                <!-- 标题 -->

                <div class="title"><span
                        v-if="articleInfo.status == 0"
                        class="tag tag-no-audit"
                    >待审核</span>{{ articleInfo.title
                    }}
                </div>
                <!-- 用户信息 -->
                <div class="user-info">
                    <Avatar
                        :userId="articleInfo.userId"
                        :width="50"
                    ></Avatar>
                    <div class="user-info-detail">
                        <router-link
                            :to="`/user/${articleInfo.userId}`"
                            class="nickName"
                        >{{ articleInfo.nickName
                            }}</router-link>
                        <div class="time-info">
                            <span>{{ articleInfo.postTime }}</span>
                            <span class="address">&nbsp;-&nbsp;{{ articleInfo.userIpAddress }}</span>
                            <span class="iconfont icon-eye-solid">
                                {{ articleInfo.readCount == 0 ? "阅读" : articleInfo.readCount }}
                            </span>
                            <router-link
                                v-if="articleInfo.userId == (currentUserInfo?.userId || '')"
                                class="a-link btn-edit"
                                :to="`/editPost/${articleInfo.articleId}`"
                            >
                                <span class="iconfont icon-edit">编辑</span>
                            </router-link>
                        </div>
                    </div>
                </div>
                <!-- 文章详情 -->
                <div
                    class="detail"
                    id="detail"
                    v-html="articleInfo.content"
                >
                </div>
            </div>
            <!-- 附件 -->
            <div
                class="attachment-panel"
                v-if="attachment"
                id="view-attachment"
            >
                <div class="title">附件</div>
                <div class="attachment-info">
                    <div class="iconfont icon-zip item"></div>
                    <div class="file-name item">{{ attachment.fileName }}</div>
                    <div class="size item">{{ proxy.Utils.sizeToStr(attachment.fileSize) }}</div>
                    <div class="item">需要<span class="integrals">{{ attachment.integral
                            }}</span>积分</div>
                    <div class="donwload-count item">已下载{{ attachment.downloadCount }}</div>
                    <el-button
                        type="primary"
                        size="small"
                        @click="downloadAttachment(attachment.fileId)"
                    >下载</el-button>
                </div>
            </div>
            <!-- 评论 -->
            <div
                class="comment-panel"
                id="view-comment"
                v-if="showComment && articleInfo.status == 1"
            >
                <CommonList
                    :articleId="articleInfo.articleId"
                    :articleUserId="articleInfo.userId"
                    @updateCommentCount="updateCommentCount"
                ></CommonList>
            </div>
        </div>
        <!-- 目录 -->
        <div class="toc-panel">
            <div class="top-containner">
                <div class="toc-title">
                    <span>目录</span>
                </div>
                <div class="toc-list">
                    <template v-if="tocArray.length == 0">
                        <div class="no-toc">暂无目录</div>
                    </template>
                    <template v-else>
                        <div
                            v-for="toc in tocArray"
                            :key="toc.id"
                        >
                            <span
                                @click="gotoAnchor(toc.id)"
                                :class="['toc-item', toc.id == anchorId ? 'active' : '']"
                                :style="{ 'padding-left': toc.level * 15 + 'px' }"
                            >{{ toc.title }}</span>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
    <!-- 快捷操作 -->
    <div
        class="quick-panel"
        :style="{ left: quickPanelLeft + 'px' }"
    >
        <!-- 点赞 -->
        <el-badge
            :value="articleInfo.goodCount"
            type="info"
            :hidden="!articleInfo.goodCount > 0"
            badge-class="badge-Detail"
        >
            <div
                class="quick-item"
                @click="doLikeHandler"
            >
                <span :class="['iconfont icon-good', haveLike ? 'have-link' : '']"></span>
            </div>
        </el-badge>
        <!-- 评论 -->
        <el-badge
            v-if="showComment"
            :value="articleInfo.commentCount"
            type="info"
            :hidden="!articleInfo.commentCount > 0"
            @click="goToPosition('view-comment')"
            badge-class="badge-Detail"
        >
            <div class="quick-item">
                <span class="iconfont icon-comment"></span>
            </div>
        </el-badge>
        <!-- 附件 -->
        <div
            class="quick-item"
            @click="goToPosition('view-attachment')"
        >
            <span class="iconfont icon-attachment"></span>
        </div>
        <!-- 图片预览 -->
        <ImageViewer
            ref="imageViewerRef"
            :imageList="previewImgList"
        ></ImageViewer>
    </div>
</template>

<script setup>
import { watch, ref, reactive, getCurrentInstance, nextTick, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import hljs from 'highlight.js';
import "highlight.js/styles/atom-one-light.css"
import CommonList from './CommonList.vue';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const store = useStore();

const api = {
    getArticleInfo: '/forum/getArticleDetail',
    doLike: '/forum/doLike',
    getUserDownloadInfo: '/forum/getUserDownloadInfo',
    attachmentDownload: '/api/forum/attachmentDownload'
}

const articleInfo = ref({})
const attachment = ref({})
// 是否点赞
const haveLike = ref(false)

const getArticleInfo = async (articleId) => {
    let result = await proxy.Request({
        url: api.getArticleInfo,
        params: {
            articleId: articleId
        }
    });
    if (!result) {
        return
    };

    articleInfo.value = result.data.forumArticle
    attachment.value = result.data.attachment
    haveLike.value = result.data.haveLike

    store.commit("setactiveBoardId", result.data.forumArticle.boardId)
    store.commit("setactivePBoardId", result.data.forumArticle.pBoardId)

    //文章图片预览
    imagePreview();
    // 代码高亮
    highLightCode();
    // 获取目录
    makeToc();
}



// 监听用户登录信息
const currentUserInfo = ref(null)
watch(() => store.state.loginUserInfo, (newVal, oldVal) => {
    currentUserInfo.value = newVal;
}, { immediate: true, deep: true });

onMounted(() => {
    getArticleInfo(route.params.articleId);
})

// 快捷操作
const quickPanelLeft = (window.innerWidth - proxy.globalInfo.bodyWidth) / 2 - 110;

// 定位
const goToPosition = (domId) => {
    document.querySelector('#' + domId).scrollIntoView();
}

const doLikeHandler = async () => {
    if (!store.getters.getLoginUserInfo) {
        store.commit('showLogin', true);
        return;
    }
    let result = await proxy.Request({
        url: api.doLike,
        params: {
            articleId: articleInfo.value.articleId
        }
    })
    if (!result) {
        return;
    }
    haveLike.value = !haveLike.value
    let goodCount = 1;
    if (!haveLike.value) {
        goodCount = -1;
    }
    articleInfo.value.goodCount += goodCount
}

const downloadAttachment = async (fileId) => {
    const currentUserInfo = store.getters.getLoginUserInfo
    if (!currentUserInfo) {
        store.commit('showLogin', true);
        return;
    }
    let result = await proxy.Request({
        url: api.getUserDownloadInfo,
        params: {
            fileId: fileId
        }
    })
    if (!result) {
        return;
    }

    // 零积分
    if (attachment.value.integral == 0 || currentUserInfo.userId == articleInfo.value.userId) {
        downloadDo(fileId)
        return;
    }

    // 判断用户是否已下载
    if (result.data.haveDownload) {
        downloadDo(fileId)
        return;
    }


    // 判断用户积分是否足够
    if (result.data.userIntegral < attachment.value.integral) {
        proxy.Message.warning("您的积分不足，无法下载")
        return
    }

    proxy.Confirm(`你还有${result.data.userIntegral}积分，当前下载会扣除${attachment.value.integral}积分，确定要下载吗？`, () => {
        downloadDo(fileId)
    })

}

const downloadDo = (fileId) => {
    document.location.href = api.attachmentDownload + '?fileId=' + fileId;
    attachment.value.downloadCount += 1;
}

// 图片预览
const imageViewerRef = ref(null)
const previewImgList = ref([]);
const imagePreview = () => {
    nextTick(() => {
        const imageNodeList = document.querySelector('#detail').querySelectorAll("img");
        const imageList = [];
        imageNodeList.forEach((item, index) => {
            const src = item.getAttribute("src")
            imageList.push(src);
            item.addEventListener("click", () => {
                if (imageViewerRef.value) {
                    imageViewerRef.value.show(index);
                }
            })
        })
        previewImgList.value = imageList
    })
}

// 代码高亮
const highLightCode = () => {
    nextTick(() => {
        let blocks = document.querySelectorAll('pre code');
        blocks.forEach((item) => {
            hljs.highlightBlock(item)
        })
    })
}

// 更新评论数
const updateCommentCount = (count) => {
    articleInfo.value.commentCount = count;
}

// 获取目录
const tocArray = ref([]);
const makeToc = () => {
    nextTick(() => {
        const tocTags = ['H1', 'H2', 'H3', 'H4', 'H5']
        const contentDom = document.querySelector('#detail')
        const childNodes = contentDom.childNodes;
        let index = 0
        childNodes.forEach(item => {
            let tagName = item.tagName;
            if (tagName == undefined || !tocTags.includes(tagName.toUpperCase())) {
                return true;
            }
            index++;
            let id = 'toc' + index;
            item.setAttribute('id', id)
            tocArray.value.push({
                id: id,
                title: item.innerText,
                level: Number.parseInt(tagName.substring(1)),
                offsetTop: item.offsetTop
            })
        })
    })
}

const anchorId = ref(null)
const gotoAnchor = (domId) => {
    const dom = document.querySelector('#' + domId);
    dom.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    })
}

const listenerScroll = () => {
    let currentScrollTop = getScrollTop();
    tocArray.value.some((item, index) => {
        if (
            (index < tocArray.value.length - 1 && currentScrollTop >= item.offsetTop && currentScrollTop < tocArray.value[index + 1].offsetTop) ||
            (index == tocArray.value.length - 1 && currentScrollTop >= item.offsetTop)
        ) {
            anchorId.value = item.id;  // 设置 anchorId
            return true;  // 找到匹配项后停止循环
        }
    });
};


// 获取滚动条高度
const getScrollTop = () => {
    let getScroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    return getScroll;
}

onMounted(() => {
    window.addEventListener("scroll", listenerScroll, false)
})

// 是否展示评论区
const showComment = ref(false)

// 监听系统设置
watch(() => store.state.sysSetting, (newVal, oldVal) => {
    if (newVal) {
        showComment.value = newVal.commentOpen
    }
}, { immediate: true, deep: true });
</script>

<style lang="scss">
.badge-Detail {
    top: 5px !important;
    right: 15px !important;
}

.article-detail-body {
    position: relative;

    .board-info {
        line-height: 30px;

        .icon-right {
            margin: 0px 10px;
        }
    }

    .detail-container {
        .article-detail {
            background: #fff;
            padding: 15px;

            .title {
                font-weight: bolder;
                color: #000;
            }

            .user-info {
                margin-top: 15px;
                display: flex;
                padding-bottom: 10px;
                border-bottom: 1px solid #ddd;

                .user-info-detail {
                    margin-left: 10px;

                    .nickName {
                        text-decoration: none;
                        color: #4e5969;
                        font-size: 15px;
                    }

                    .nickName:hover {
                        color: var(--link);
                    }

                    .time-info {
                        margin-top: 5px;
                        font-size: 13px;
                        color: var(--text2);

                        .iconfont {
                            margin-left: 10px;
                        }

                        .iconfont::before {
                            padding-left: 3px;
                        }

                        .btn-edit {
                            .iconfont {
                                font-size: 13px;
                            }
                        }
                    }
                }
            }

            .detail {
                letter-spacing: 1px;
                line-height: 21px;
                max-width: 80% !important;

                a {
                    text-decoration: none;
                    color: var(--link);
                }


            }

            img {
                max-width: 90%;
                cursor: pointer;
            }
        }


    }

    .attachment-panel {
        margin-top: 20px;
        background: #fff;
        padding: 20px;

        .title {
            font-size: 18px;
            color: #000;
        }

        .attachment-info {
            margin-top: 10px;
            display: flex;
            align-items: center;
            color: #9f9f9f;

            .item {
                margin-right: 10px;
            }

            .icon-zip {
                font-size: 20px;
                color: #6ca1f7;
            }

            .file-name {
                color: #6ca1f7;
            }

            .integrals {
                color: red;
                padding: 0 5px;
            }
        }
    }

    .comment-panel {
        margin-top: 20px;
        background: #fff;
        padding: 20px;
    }
}

.quick-panel {
    position: fixed;
    width: 50px;
    top: 150px;



    .quick-item {
        display: flex;
        width: 50px;
        height: 50px;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        background: #fff;
        margin-bottom: 30px;
        cursor: pointer;

        .iconfont {
            font-size: 22px;
            color: var(--text2);
        }

        .have-link {
            color: red;
        }
    }
}


.toc-panel {
    position: absolute;
    right: 0px;
    top: 30px;
    width: 280px;
    height: 500px;

    .top-containner {
        position: fixed;
        background: white;
        width: 300px;
        // height: 500px;

        .toc-title {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }

        .toc-list {
            max-height: calc(100vh - 200px);
            overflow: auto;
            padding: 5px;
        }

        .no-toc {
            text-align: center;
            line-height: 40px;
            font-size: 13px;
        }

        .toc-item {
            cursor: pointer;
            line-height: 35px;
            overflow: hidden; // 内容过长时省略
            display: block;
            white-space: nowrap;
            text-overflow: ellipsis;
            border-radius: 3px;
            font-size: 14px;
            border-left: 2px solid #fff;
        }

        .toc-item:hover {
            background: #e4e3e3;
        }

        .active {
            border-left: 2px solid #6ca1f7;
            border-radius: 0px 3px 3px 0px;
            background: #e4e3e3;
        }
    }
}
</style>
